package com.gill.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gill.exception.CommonServiceException;
import com.gill.service.FilmService;
import com.gill.vo.*;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

@Slf4j
@RequestMapping("/film")
@RestController
public class FilmController {

    @Autowired
    private FilmService filmService;

    /**
     * 获取演员列表
     */
    @GetMapping(value = "/actors")
    public BaseResponseVO describeActors(BasePageVO basePageVO) throws CommonServiceException {
        // 检查入参
        basePageVO.checkParam();
        // 调用逻辑层，获取返回参数
        IPage<DescribeActorsRespVO> results = filmService.describeActors(basePageVO.getNowPage(),basePageVO.getPageSize());
        Map<String, Object> actors = descrbePageResult(results, "actors");
        return BaseResponseVO.success(actors);
    }

    /**
     * 获取电影列表
     */
    @GetMapping("/films")
    public BaseResponseVO describeFilms(HttpServletRequest request, BasePageVO basePageVO) throws CommonServiceException {
        // 检查入参
        basePageVO.checkParam();
        // 调用逻辑层，获取返回参数
        IPage<DescribeFilmsRespVO> results = filmService.describeFilms(basePageVO.getNowPage(),basePageVO.getPageSize());
        Map<String, Object> films = descrbePageResult(results, "films");
        return BaseResponseVO.success(films);
    }

    /**
     * 根据电影主键获取电影信息
     */
    @GetMapping(value = "/{filmId}")
    public BaseResponseVO describeFilmById(@PathVariable("filmId")String filmId) throws CommonServiceException {

        DescribeFilmRespVO describeFilmRespVO = filmService.describeFilmById(filmId);
        if(describeFilmRespVO == null){
            return BaseResponseVO.success();
        }else{
            return BaseResponseVO.success(describeFilmRespVO);
        }

    }

    /**
     * 添加电影
     */
    @PostMapping(value = "/add")
    public BaseResponseVO saveFilmInfo(@RequestBody FilmSavedReqVO filmSavedReqVO) throws CommonServiceException {

        // 为了简单，先不做校验
//        filmSavedReqVO.checkParam();

        filmService.saveFilm(filmSavedReqVO);

        return BaseResponseVO.success();
    }



    /**
     * 构造返回结果
     */
    private Map<String,Object> descrbePageResult(IPage page, String title){
        Map<String,Object> result = Maps.newHashMap();

        result.put("totalSize",page.getTotal());
        result.put("totalPages",page.getPages());
        result.put("pageSize",page.getSize());
        result.put("nowPage",page.getCurrent());

        result.put(title, page.getRecords());

        return result;
    }

}
